package cn.sciento.boot.platform.data.autoconfigure;

import cn.sciento.boot.platform.data.permission.interceptor.FilterSqlInterceptor;
import cn.sciento.boot.platform.data.permission.builder.PermissionSqlBuilder;
import cn.sciento.boot.platform.data.permission.repository.DefaultPermissionSqlRepository;
import cn.sciento.boot.platform.data.permission.repository.PermissionSqlRepository;
import cn.sciento.core.redis.RedisHelper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.HashSet;

/**
 * <p>
 * 数据屏蔽自动化配置
 * </p>
 *

 */
@Configuration
@EnableConfigurationProperties(PermissionDataProperties.class)
@ConditionalOnProperty(prefix = "stong.data.permission", name = "enabled", havingValue = "true", matchIfMissing = true)
public class PermissionDataAutoConfiguration {


    @Bean
    @ConditionalOnMissingBean
    public PermissionSqlRepository permissionSqlRepository(RedisHelper redisHelper) {
        return new DefaultPermissionSqlRepository(redisHelper);
    }

    @Bean
    @ConditionalOnMissingBean
    public PermissionSqlBuilder permissionDataInterceptor(ApplicationContext applicationContext,
                                                          PermissionSqlRepository permissionSqlRepository,
                                                          PermissionDataProperties permissionDataProperties) {
        // 检测上下文中的拦截器
        String[] beanNames = applicationContext.getBeanNamesForType(FilterSqlInterceptor.class);
        return new PermissionSqlBuilder(permissionSqlRepository, permissionDataProperties, new HashSet<>(Arrays.asList(beanNames)));
    }
}
